let keys = 'SGXBZ-6X3K6-NYLSF-MALZD-QC6PK-BABOS';
let network = require("../../utils/network/network.js")
let api = require("../../utils/network/config.js").api;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowCamera: false,
    image: "",
    isShowImage: false,
    district: "",
    width: 0,
    height: 0,
    gap: 20,
    top_offset: 120,
    lineSize: 50,
    hasTakePhoto: false,
    src: "",
    logo: "../../assets/imgs/takephoto.jpg",

    // 竹签
    stickOpt: [],
    stickList: [],
    currentStickIndex: 0,

    currentResult: {
      detectNum: -1,
      detectTime: '',
      resultUrl: 'https://oss.flik1337.com/9022ced0-7deb-11ed-85cf-0242ac110004',
      detectTime: '2022-12-18 16:38:52',

    },
    detectList: [],
    resultButtons: [{
        type: 'default',
        className: '',
        text: '辅助操作',
        value: 0
      },
      {
        type: 'primary',
        className: '',
        text: '主操作',
        value: 1
      }
    ],


    // 绘制
    canvas: null,
    canvasContext: null,
    showResult: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    var that = this
    that.getStickList()
    that.ctx = wx.createCameraContext()

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          width: res.windowWidth,
          height: res.windowHeight
        })
      }
    })
  },
  onShow: function () {
    var that = this
    wx.authorize({
      scope: 'scope.camera',
      success: function (res) {
        that.setData({
          isShowCamera: true,
        })
      },
      fail: function (res) {
        console.log("" + res);
        wx.showModal({
          title: '请求授权您的摄像头',
          content: '如需正常使用此小程序功能，请您按确定并在设置页面授权用户信息',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              wx.openSetting({
                success: function (res) {
                  console.log('成功');
                  console.log(res);
                  if (res.authSetting['scope.camera']) { //设置允许获取摄像头
                    console.log('设置允许获取摄像头')
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    that.setData({
                      isShowCamera: true,
                    })
                  } else { //不允许
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                    wx.navigateBack({
                      delta: 1
                    })
                  }
                }
              })
            } else { //取消
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 1000
              })
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      }
    })
  },
  onReady: function () {
    let that = this
    const query = this.createSelectorQuery()
    query.select('#canvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        console.log(res)
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        canvas.width = that.data.width
        canvas.height = that.data.height

        that.setData({
          canvas: canvas,
          canvasContext: ctx
        })
      })

  },
  takePhoto: function () {
    var that = this
    let width = that.data.width
    let height = that.data.height
    let gap = that.data.gap
    that.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log(res)
        let ctx = that.data.canvasContext
        let canvas = that.data.canvas
        wx.setStorage({
          key: 'originalImagePath',
          data: res.tempImagePath,
        })
        // wx.navigateTo({
        //   url: 'upload?path=' + res.tempImagePath + '&char=0'
        // })
        console.log(res.tempImagePath)
        console.log(ctx)
        //ctx.drawImage(res.tempImagePath, 0, 0)

        let img = canvas.createImage()
        img.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.drawImage(img, 0, 0, width, height)
        }
        img.src = res.tempImagePath
        let x = gap
        let y = (height - width) / 2 + gap - that.data.top_offset
        let size = width - 2 * gap
        setTimeout(() => {
          wx.canvasToTempFilePath({
            //canvasId: 'canvas',
            width: size,
            height: size,
            x: x,
            y: y,
            fileType: 'png',
            canvas: canvas,

            success(res) {
              console.log(res.tempFilePath)
              wx.getImageInfo({
                src: res.tempFilePath,
                success(res) {
                  console.log(res)
                }
              })

              that.detect(res.tempFilePath)
            }
          })
        }, 300);
      }
    })
  },
  detect(filePath) {
    wx.showLoading({
      title: '努力识别中...',
    })
    let that = this
    wx.uploadFile({
      //url: 'http://region-8.seetacloud.com:12079/predict',
      url: api.base_url + api.predict,
      filePath: filePath,
      name: 'pic_name',
      success(res) {

        res = JSON.parse(res.data)
        console.log(res)
        // 构造检测结果对象
        let detectResult = {}
        detectResult.detectNum = res.data.count
        detectResult.resultUrl = res.data.imageUrl
        detectResult.detectTime = res.data.detectTime
        //detectResult.userId = getApp().globalData.userInfo.uid
        detectResult.userId = 22
        detectResult.stickId = that.data.stickList[that.data.currentStickIndex].stickId

        that.setData({
          currentResult: detectResult
        })
        that.openModal()
        wx.hideLoading()
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  openModal() {
    this.setData({
      showResult: true,
    })
  },
  closeModal() {
    this.setData({
      showResult: false,
    })
  },
  onMenuChange({
    detail
  }) {
    this.setData({
      currentStickIndex: detail
    })
  },
  // 添加至结算列表
  addToCount() {
    let that = this
    let detectList = that.data.detectList
    let detectResult = that.data.currentResult
    detectResult.stick = that.data.stickList[that.data.currentStickIndex]

    detectList.push(detectResult)
    that.setData({
      detectList: detectList
    })
    that.closeModal()
  },
  // 获取商家竹签列表
  getStickList() {
    let that = this
    network.fetch({
        url: api.stick_list,
        inBody: false,
        data: {
          //userId: getApp().globalData.userInfo.uid
          userId: 22
        },
        method: 'GET',
      })
      .then(res => {
        console.log(res)
        let stickList = res.data
        let stickMenuList = []
        stickList.forEach((element, idx) => {
          let stickMenuItem = {
            text: element.stickName,
            value: idx
          }
          stickMenuList[idx] = stickMenuItem
        });
        that.setData({
          stickList: res.data,
          stickOpt: stickMenuList
        })
      })
  },
  // 全部结算
  allCount() {

    let detectList = JSON.stringify(this.data.detectList)
    wx.navigateTo({
      url: './../count/count?detectList=' + detectList,
    })
  }


})